function queryStringify(obj){
  let str = ''
  for (let k in obj) str += `${k}=${obj[k]}&`
  return str.slice(0,-1)
}
function ajax(options){
  let defaultoptions = {
    url:"",
    method:"GET",
    async:true,
    data:{},
    headers:{"Content-Type":"application/x-www-form-urlencoded"},
    success:function(){},
    error:function(){}
  }
  let {url,method,async,data,headers,success,error} = {
    ...defaultoptions,
    ...options
  }


  //输入为对象则json化，否则则使用上面方法进行form拼接
  if(typeof data === 'object' && headers["content-type"]?.indexOf("json") > -1){
    data = JSON.stringify(data)
  }else{
    data = queryStringify(data)
  }
  //如果是get请求并且有参数，则直接组装拼接url信息
  if(/^get$/i.test(method) && data) url += '?' + data

  const xhr = new XMLHttpRequest()
  xhr.open(method, url, async)
  xhr.onload = function(){
    if(!/^2\d{2}$/.test(xhr.status)){
      error(`错误状态码:${xhr.status}`)
      return
    }

    try{
      let result = JSON.parse(xhr.responseText)
      success(result)
    }catch(err){
      error('解析失败!')
    }
  }
  for(let k in headers) xhr.setRequestHeader(k, headers[k])

  if(/^get$/i.test(method)){
    xhr.send()
  }else{
    xhr.send(data)
  }
}


export default ajax
